package com.example.springbootweb_comprehensiveexample.service.impl;


import com.example.springbootweb_comprehensiveexample.pojo.DeptLog;
import com.example.springbootweb_comprehensiveexample.service.DeptLogService;
import com.example.springbootweb_comprehensiveexample.service.DeptService;
import com.example.springbootweb_comprehensiveexample.mapper.DeptMapper;
import com.example.springbootweb_comprehensiveexample.mapper.EmpMapper;
import com.example.springbootweb_comprehensiveexample.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    /**
     * 删除部门
     * @param id
     */
    @Transactional (rollbackFor = Exception.class)//已经交给spring进行事务管理
    @Override
    public void delete(Integer id) throws Exception {
        try {
            deptMapper.delete(id);
            //模拟抛出异常
            //int i = 1/0;
            empMapper.deleteEmpByDeptId(id);
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("此次解散的部门是" + id +"号部门");
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }

    //更新部门
     //1.根据id查询部门
    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
